package com.typhoon.spring_boot_demo1.service.impl;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.typhoon.spring_boot_demo1.bean.User;
import com.typhoon.spring_boot_demo1.service.UserService;
import com.typhoon.spring_boot_demo1.utils.BeanUtils;

@Service
public class UserServiceImpl implements UserService {

	private static Map<Long,User> cache  = new HashMap<>();
	private SoftReference<Map<Long,User>> reference = new SoftReference<>(cache);

	static {
		for(int i = 0 ;i < 1000;i ++) {
			cache.put(Long.valueOf(i),new User());
		}
		System.out.println(cache.size());
	}
	
    @Autowired
    private JdbcTemplate jdbcTemplate;

	public void create(String name, Integer age) {
		jdbcTemplate.update("insert into User(name,age) values(?,?)",name,age);
	}

	public void deleteByName(String name) {
		jdbcTemplate.update("delete from User where name = ?",name);
	}

	public Integer getAllUsers() {
		return jdbcTemplate.queryForObject("select count(1) from User", Integer.class);
	}

	public void deleteAllUsers() {
		jdbcTemplate.update("delete from User");
	}

	public User queryByPK(Long id) {
		System.out.println(1);
		Map<Long,User>  map = reference.get();
		System.out.println("softReference:" + reference);
		if(null == map) {
			return null;
		}
		System.out.println(map.size());
		String str = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
		List<String> list = new ArrayList<>();
		for(int i = 0;i < 100000;i ++) {
			list.add(i + str);
		}
		System.out.println(list.size());
		System.out.println("softReference:" + reference);


		Map<String,Object> result = jdbcTemplate.queryForMap("select * from User where id = ? ",id);
		return BeanUtils.toBean(result, User.class);
	}

}
